import * as THREE from "three";
// 功能：环境贴图

// 导入轨道控制器
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

// 1.创建场景
const scene = new THREE.Scene();
// 2. 创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);

// 设置相机位置
camera.position.set(0, 0, 10);
// 添加相机到场景中
scene.add(camera);

// 设置cube纹理加载器
const cubeTextureLoader = new THREE.CubeTextureLoader();
const envMapTexture = cubeTextureLoader.load([
  require("../assets/img/environmentMaps/1/px.jpg"),
  require("../assets/img/environmentMaps/1/nx.jpg"),
  require("../assets/img/environmentMaps/1/py.jpg"),
  require("../assets/img/environmentMaps/1/ny.jpg"),
  require("../assets/img/environmentMaps/1/pz.jpg"),
  require("../assets/img/environmentMaps/1/nz.jpg"),
]);// p-正方向，n-负方向

// 创建球体
const sphereTexture = new THREE.SphereGeometry(1, 20, 20);
// 材质
const material = new THREE.MeshStandardMaterial({
  metalness: 0.7,
  roughness: 0,
  // envMap: envMapTexture,
});

// 关联几何体和材质
const spher = new THREE.Mesh(sphereTexture, material);

// 添加几何体到场景
scene.add(spher);

// 给场景添加背景
scene.background = envMapTexture;
// 给场景所有的物体添加默认的环境贴图
scene.environment = envMapTexture;

// 4. 初始化渲染器
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
// 将webgl渲染的canvas内容添加到body
document.body.appendChild(renderer.domElement);

const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;

// 添加坐标轴辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

function animate() {
  controls.update();
  renderer.render(scene, camera);
  // 渲染下一帧的时候就调用animate
  requestAnimationFrame(animate);
}
animate();

// 监听画面变化
window.addEventListener("resize", () => {
  const iwidth = window.innerWidth;
  const iheigt = window.innerHeight;
  //更新摄像头
  camera.aspect = iwidth / iheigt;
  // 更新摄像机投影矩阵
  camera.updateProjectionMatrix();
  // 更新渲染器
  renderer.setSize(iwidth, iheigt);
  // 设置渲染器像素比
  renderer.setPixelRatio(window.devicePixelRatio);
});
